package command

import (
	"encoding/csv"
	"gitee.com/moyrn/sa/store"
	"gitee.com/moyrn/sa/store/models"
	"github.com/spf13/cobra"
	"os"
	"strconv"
	"time"
)

var OutputCmd = &cobra.Command{
	Use:   "output",
	Short: "导出已爬取的数据",
	Long:  "导出已爬取的数据",
	Run: func(cmd *cobra.Command, args []string) {
		if err := taskToCSV(e.Store.All(), filename); err != nil {
			store.Log.Panic("taskToCSV", err)
		}
		os.Exit(0)
	},
}

func init() {
	OutputCmd.Flags().StringVarP(&filename, "filename", "f", "output.csv", "请输入导出文件名称")
}

func taskToCSV(tasks []models.Task, filename string) error {
	file, err := os.Create(filename)
	if err != nil {
		return err
	}
	defer file.Close()
	csvFile := csv.NewWriter(file)
	if err := csvFile.Write([]string{"ID", "CreatedAt", "UpdatedAt",
		"Url", "Params", "ParserFunction", "FailedReason",
		"Status", "Title", "Content", "Remark"}); err != nil {
		return err
	}
	for _, t := range tasks {
		if err := csvFile.Write([]string{
			toString(t.ID),
			toString(t.CreatedAt),
			toString(t.UpdatedAt),
			toString(t.Url),
			toString(t.Params),
			toString(t.ParserFunction),
			toString(t.FailedReason),
			toString(t.Status),
			toString(t.Title),
			toString(t.Content),
			toString(t.Remark),
		}); err != nil {
			store.Log.Info("output", err)
		}
	}
	return nil
}

func toString(i interface{}) string {
	switch v := i.(type) {
	case int:
		return strconv.Itoa(v)
	case uint:
		return strconv.Itoa(int(v))
	case time.Time:
		return v.String()
	case string:
		return v
	}
	return "don't support this type"
}
